<?php

// created 6/13/12


// check user login
session_start();
if (isset($_SESSION["user"]) && !empty($_SESSION["user"])) {
//echo $_SESSION["user"];
    if (isset($_SESSION["active_character"]) && !empty($_SESSION["active_character"])) {

//include 'function_library.php';


class Character extends CI_Controller {

	public function __construct() {
            parent::__construct(); 

            $this->load->helper('form','dynasties2_common');
            
	}////// 
        ////////////////////////////////////////////////
        
        public function index() {
            
            
            //$data = $this->input->post('whichCharacter');
            //$_SESSION["active_character"] = $data;
            
            //echo $data;
            
            $this->load->view('navigation_bar_view');
            $this->load->view('CHAR_primary_view');
            
            /////////////////////////////////////
            ////// show titles on the index screen
            $this->load->model('query_models');
             $titles = $this->query_models->my_titles();
             if ($titles) {
                $data['title_data'] = $titles;
                foreach ($titles as $row) {
                    //echo $row->getRegionLink()->getId();
                    $region_data = $this->doctrine->em->find('ORM\Dynasties2\Regions', $row->getRegionLink()->getId());
                    //echo $region_data->getRegionName();
                    $data['region_data'][] = $region_data;
                    
                    //$claim_data = $this->doctrine->em->find('ORM\Dynasties2\Claims', $row->getRegionLink()->getId());
                    $claim_data = $this->doctrine->em->getRepository('ORM\Dynasties2\Claims')->findBy(array('titleLink' => $row->getId()));
                    if ($claim_data) {
                        //echo "Claim1";
                        // there are claims against me!
                        $data['claim_data'] = $claim_data;
                    }
                }
                
                $this->load->view('CHAR_mytitles_view',$data);
            }
            //// end show titles on index screen
            ///////////////////////////////////////
            
            
            /////////////////////////////////////
            ////// show war data on the index screen
            $this->load->model('query_models');
            $wars = $this->query_models->my_wars();
            if ($wars) {
                $data['war_data'] = $wars;
                
                //$this->load->model('query_models');
                $army = $this->query_models->my_army();
                if ($army) {
                    //$army_id = $army->getId();
                    //print_r($army);
                    foreach ($army as $row) $army_id = $row->getId();
                    $data['army_data'] = $army;
                    $armyforces = $this->query_models->my_army_forces($army_id);
                    $data['armyforces_data'] = $armyforces;
                }
                
                
                $this->load->view('CHAR_mywars_view',$data);
            }  /// end if wars
            
            //// end show war data on index screen
            ///////////////////////////////////////
            
            
            
        }  ////// end of function index /////////////////////////
        /////////////////////////////////////////////////////////
        
        public function display_my_family() {
            
            $character_id = $_SESSION["active_character"];
            $this->load->view('navigation_bar_view');
            $this->load->view('CHAR_myfamily_view');
            
            
            // get my family
            
            // display my family
            
        }   ////// end of function display_my_family //////////////////////
        ////////////////////////////////////////////////
         
        
       
        
         public function display_my_titles() {
            
             $this->load->view('navigation_bar_view');
             
             $this->load->model('query_models');
             $titles = $this->query_models->my_titles();
             if ($titles) {
                $data['title_data'] = $titles;
                
                $this->load->view('CHAR_mytitles_view',$data);
            }
             
             
            
            
        }   ////// end of function display_my_titles //////////////////////
        ////////////////////////////////////////////////
        
        public function display_my_claims() {
            
             $this->load->view('navigation_bar_view');
             
             
             ////////////////
             $character_id = $_SESSION["active_character"];
             $query = $this->doctrine->em->createQuery("SELECT u 
                FROM ORM\Dynasties2\Claims u 
                WHERE u.characterLink = $character_id
                    ");

            $my_claims = $query->getResult();
            
            $claimarray = array();
            $data = array();
            foreach ($my_claims as $row) {
                //echo "<br>I have claimed " . $row->getTitleLink()->getId();
                
                $already_war = $this->doctrine->em->getRepository('ORM\Dynasties2\Wars')->findOneBy(array('whichClaim' => $row->getId()));
                if($already_war) {
                    
                } else {
                    $claimarray[$row->getId()][] = $row->getPending();
                    $claimarray[$row->getId()][] = $row->getTitleLink()->getId();
                }
                
                
            }
            
            if ($claimarray) $data['claims'] = $claimarray;
             
             //print_r($claimarray);
             
             //////////////////
             $this->load->view('CHAR_myclaims_view',$data);
            
            
        }   ////// end of function display_my_claims //////////////////////
        ////////////////////////////////////////////////
        
        public function display_claims_against_me() {
            
             $this->load->view('navigation_bar_view');
             $this->load->view('CHAR_claimsagainstme_view');
            
            
        }   ////// end of function display_my_claims //////////////////////
        ////////////////////////////////////////////////
        
        public function display_my_vassals() {
            
             $this->load->view('navigation_bar_view');
             $this->load->view('CHAR_myvassals_view');
            
            
        }   ////// end of function display_my_vassals //////////////////////
        ////////////////////////////////////////////////
        
        public function display_my_wars() {
            
             $this->load->view('navigation_bar_view');
             $this->load->view('CHAR_mywars_view');
            
            
        }   ////// end of function display_my_vassals //////////////////////
        ////////////////////////////////////////////////
     
        public function my_neighbors() {
            
             $this->load->view('navigation_bar_view');
             
             /////////////////////////////////////
             $character_id = $_SESSION["active_character"];
             $duchy = $this->doctrine->em->getRepository('ORM\Dynasties2\Duchies')->findOneBy(array('characterLink' => $character_id));
                if ($duchy) {
                    
                    $duchy_id = $duchy->getId();
                    
                     $query = $this->doctrine->em->createQuery("SELECT u 
                        FROM ORM\Dynasties2\Duchyregions u 
                        WHERE u.whichDuchy = $duchy_id
                            ");

                    $duchy_regions = $query->getResult();
                    
                    if ($duchy_regions) {

                        $sqlstring = "SELECT u 
                                FROM ORM\Dynasties2\Regionneighbors u ";
                        $myregions = array();
                        foreach ($duchy_regions as $key => $row) {
                            $myregions[] = $row -> getWhichRegion();
                            //echo $key . "- " . $row -> getRegionLink()->getId() . ", ";



                            if ($key == '0') {
                                $val = $row -> getWhichRegion();
                                $sqlstring = $sqlstring . "WHERE u.whichRegion = '$val'";
                            } else {
                                $val = $row -> getWhichRegion();
                                $sqlstring = $sqlstring . " OR u.whichRegion = '$val'";
                            }

                        }
                        //echo "<br>"; 


                        $query = $this->doctrine->em->createQuery("$sqlstring");

                        $neighbors = array();
                        $neighbor_data = $query->getResult();
                        foreach ($neighbor_data as $row) {
                            //echo $row->getNeighborRegion() . ", ";
                            if (!in_array($row->getNeighborRegion(), $myregions)) {
                                $neighbors[] = $row->getNeighborRegion();
                                // the above code adds regions to $neighbors() array, which is regions that are okay to claim
                                // 
                            } else {
                                //echo "<br>Removed a neighbor! " . $row->getNeighborRegion() . " test</br> ";
                            }  
                        }
                    }
                    
                    
                } else {

                    $query = $this->doctrine->em->createQuery("SELECT u 
                            FROM ORM\Dynasties2\Titles u 
                            WHERE u.characterLink = $character_id
                                ");

                    $owned_regions = $query->getResult();

                    $sqlstring = "SELECT u 
                                FROM ORM\Dynasties2\Regionneighbors u ";

                    if ($owned_regions) {

                        $myregions = array();
                        foreach ($owned_regions as $key => $row) {
                            $myregions[] = $row -> getRegionLink()->getId();
                            //echo $key . "- " . $row -> getRegionLink()->getId() . ", ";



                            if ($key == '0') {
                                $val = $row -> getRegionLink()->getId();
                                $sqlstring = $sqlstring . "WHERE u.whichRegion = '$val'";
                            } else {
                                $val = $row -> getRegionLink()->getId();
                                $sqlstring = $sqlstring . " OR u.whichRegion = '$val'";
                            }

                        }
                        echo "<br>"; 


                        $query = $this->doctrine->em->createQuery("$sqlstring");

                        $neighbors = array();
                        $neighbor_data = $query->getResult();
                        foreach ($neighbor_data as $row) {
                            //echo $row->getNeighborRegion() . ", ";
                            if (!in_array($row->getNeighborRegion(), $myregions)) {
                                $neighbors[] = $row->getNeighborRegion();
                                // the above code adds regions to $neighbors() array, which is regions that are okay to claim
                                // 
                            } else {
                                //echo "<br>Removed a neighbor! " . $row->getNeighborRegion() . " test</br> ";
                            }  
                        }
                    }
                        //print_r($neighbors);
                }  ///////// end else, the above code is for counts only, dukes are handled by preceeding half of the IF
                
                $neighbors = array_unique($neighbors);
                
                    foreach ($neighbors as $row) {
                        $title_data[$row][] = $this->doctrine->em->getRepository('ORM\Dynasties2\Titles')->findOneBy(array('regionLink' => $row));
                    }
                
                
                //////////////////////////////////////

                    $data['titledata'] = $title_data;
            //$data['neighbors'] = $neighbors;
            
             $this->load->model('query_models');
             $titles = $this->query_models->get_adjacent_titles();
             
             $this->load->view('CHAR_myneighbors_view',$data);
             
            
            
        }   ////// end of function my_neighbors //////////////////////
        ////////////////////////////////////////////////
        
        public function claim_title_select() {
            
            
             $character_id = $_SESSION["active_character"];
             
            $title_id = $this->input->post('whichTitle');
            
            

            $title_data = $this->doctrine->em->find('ORM\Dynasties2\Titles', $title_id);

            $character_data = $this->doctrine->em->find('ORM\Dynasties2\Characters', $character_id);
            
            
            $query = $this->doctrine->em->createQuery("SELECT u 
                    FROM ORM\Dynasties2\Claims u 
                    WHERE u.titleLink = $title_id
                     AND u.characterLink = $character_id
                        ");

            $existing_claims = $query->getResult();
            
            if ($existing_claims) {

                 echo "<br>Claim already exists.</br>";
                
            } else {
               $new_claim = new ORM\Dynasties2\Claims;
                $new_claim->setTitleLink($title_data);
                $new_claim->setCharacterLink($character_data);
                $new_claim->setInherhit('0');
                $new_claim->setPending('1');

                $this->doctrine->em->persist($new_claim);
                $this->doctrine->em->flush();
            }
            $this->index();
            
            
            
        }   ////// end of function claim_title_select //////////////////////
        ////////////////////////////////////////////////
        
        public function intiate_claim_war() {
            
            $this->load->helper('dynasties2_common');
            
            $character_id = $_SESSION["active_character"];
             
            $claim_id = $this->input->post('whichClaim');
            $claim_data = $this->doctrine->em->find('ORM\Dynasties2\Claims', $claim_id);
            $defender = $claim_data->getTitleLink()->getCharacterLink()->getId();
            
            $new_war = new ORM\Dynasties2\Wars;
        
            $new_war -> setAttacker($character_id);
            $new_war -> setDefender($defender);
            $new_war -> setWarType('1');
            $new_war -> setPercentage('0');
            $new_war -> setWhichClaim($claim_id);

            $this->doctrine->em->persist($new_war);
            $this->doctrine->em->flush();
            
            $new_war_participant = new ORM\Dynasties2\Warparticipants;
            $new_war_participant -> setWarLink($new_war);
            $new_war_participant -> setWhichSide($defender);
            $new_war_participant -> setWhichCharacter($defender);
            //$new_war_participant -> setWhichTitle();
            $this->doctrine->em->persist($new_war_participant);

            $new_war_participant = new ORM\Dynasties2\Warparticipants;
            $new_war_participant -> setWarLink($new_war);
            $new_war_participant -> setWhichSide($character_id);
            $new_war_participant -> setWhichCharacter($character_id);
            //$new_war_participant -> setWhichTitle();
            $this->doctrine->em->persist($new_war_participant);
            
            call_levies($character_id);
            call_levies($defender);
            
            $this->index();
            
        }   ////// end of function intiate_claim_war //////////////////////
        ////////////////////////////////////////////////
         
         
         
        
        
        
        
        
        
    }    /////////////// END: class Character extends CI_Controller 
    
    }//// END:  if (isset($_SESSION["active_character"]) && !empty($_SESSION["active_character"]))
    
}  //// END:  if (isset($_SESSION["user"]) && !empty($_SESSION["user"]))
else {
   // deny, log, redirect
    
    //$this->load->helper('url');
    //redirect('/dynasties2/start', 'location');
    
}


